package cn.airnan.dg.service;

import cn.airnan.dg.configs.Global;
import cn.airnan.dg.entity.Room;
import cn.airnan.dg.pojo.RoomListVO;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 房间相关业务逻辑
 */
@Service
public class RoomService {

    /**
     * 获取房间列表
     *
     * @return
     */
    public List<RoomListVO> getRooms() {
        List<RoomListVO> list = new ArrayList<>();
        Global.ROOMS.values().forEach(room -> {
            RoomListVO roomListVO = new RoomListVO();
            roomListVO.setId(room.getId());
            roomListVO.setMaster(room.getMaster());
            list.add(roomListVO);
        });
        return list;
    }

    /**
     * 创建房间
     *
     * @return
     */
    public Room createRoom(Room room) {
        try {
            Global.ROOMS.put(room.getId(), room);
            return room;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 判断是否可以创建房间
     *
     * @return true/false
     */
    public boolean canCreateRoom(String roomId) {
        boolean exist = Global.ROOMS.containsKey(roomId);
        if (exist) {
            return false;
        }
        return true;
    }

    /**
     * 判断是否可以加入房间
     *
     * @return true/false
     */
    public boolean canJoinRoom(String roomId) {
        int result = 5 - Global.ROOMS.get(roomId).getPlayers().size();
        // 有空位并且游戏没有开始
        if (result > 0 && !Global.ROOMS.get(roomId).isBegin()) {
            return true;
        }
        return false;
    }

}
